package xyz.lwm.lazycat.beans;

import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.annotation.BeanScan;
import xyz.lwm.lazycat.annotation.Configuration;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.utility.scan.ScanUtil;

import java.util.Arrays;

/**
 * Bean 扫描
 *
 * @author lwm
 * @see BeanScan
 */
class BeanDesignScanLoader implements BeanDesignRegistryCustomizer {

    /**
     * 配置 {@link BeanScan} 的 design
     */
    private final String[] packages;

    private final BeanDesignRegistryCustomizers registryCustomizers;

    BeanDesignScanLoader(String[] packages, BeanDesignRegistryCustomizers registryCustomizers) {
        this.packages = packages;
        this.registryCustomizers = registryCustomizers;
    }

    @Override
    public void customize(BeanDesignRegistry beanRegistry) {
        It.of(packages).let(Arrays::asList).also(pkgList ->
                pkgList.forEach(pkg ->
                        ScanUtil.scanClasses(pkg + ".**").forEach(clz ->
                                registerClass(clz, beanRegistry))));
    }

    private void registerClass(Class<?> clz, BeanDesignRegistry beanRegistry) {
        BeanDesignUtil.buildDesign(clz)
                .filter(design ->
                        design.getAnnotations().hasAnnotation(Bean.class))
                .also(beanRegistry::register)
                .filter(design ->
                        design.getAnnotations().hasAnnotation(Configuration.class))
                .also(design ->
                        registryCustomizers.add(new BeanDesignConfigurationLoader(design, registryCustomizers)));
    }

}
